<?php

declare(strict_types=1);

namespace App\CustHub\Service;

use App\CustHub\Amqp\Producers\RobotMsgProducers;
use App\CustHub\Constants\CrowSendingConstants;
use App\CustHub\Constants\SendConfigConstants;
use App\CustHub\Constants\SendFailureReasonConstants;
use App\CustHub\Constants\SendRecordStatusConstants;
use App\CustHub\Constants\SmartPushSchemeStatusConstants;
use App\CustHub\Constants\SmartPushSchemeSubStatusConstants;
use App\CustHub\Constants\SmartPushSchemeTaskStatusConstants;
use App\CustHub\Constants\SmartPushSchemeTypeConstants;
use App\CustHub\Mapper\ChRobotMapper;
use App\CustHub\Mapper\ChSendRecordMapper;
use App\CustHub\Model\ChCrowdSending;
use App\CustHub\Model\ChCrowdSendingSubTask;
use App\CustHub\Model\ChSendRecord;
use App\CustHub\Model\ChSmartPushScheme;
use App\CustHub\Model\ChSmartPushSchemeSubTask;
use App\CustHub\Model\ChSmartPushSchemeTask;
use App\Robot\Dto\CommonJobDto;
use App\Robot\Dto\RobotMsgDto;
use App\Robot\Job\CommonJob;
use App\Robot\Service\SendRecordMessageHandlerService;
use Carbon\Carbon;
use Hyperf\Amqp\Producer;
use Hyperf\Coroutine\Coroutine;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Mine\Abstracts\AbstractService;
use Mine\MineModel;
use function Hyperf\Collection\data_get;
use function Hyperf\Coroutine\co;

class ChSendRecordService extends AbstractService
{
    public $mapper;

    #[Inject]
    protected ChRobotMapper $robotMapper;

    public function __construct(ChSendRecordMapper $mapper)
    {
        $this->mapper = $mapper;
    }

    /**
     * @param array $data
     * @return array
     */
    public function list(array $data): array
    {
        $taskId = data_get($data,'task_id','');
        $taskType = data_get($data,'task_type','');
        $contactId = data_get($data,'contact_id','');
        $robotId = data_get($data,'robot_id','');
        $status = data_get($data,'status','');
        $startTime = data_get($data,'start_time','');
        $endTime = data_get($data,'end_time','');
        $pageSize = (int)data_get($data,'page_size',MineModel::PAGE_SIZE);

        $paginate = Db::table('ch_send_record as sr')
            ->selectRaw('sr.id,sr.robot_id,r.nickname,r.avatar,r.corp_name as robot_corp_name,sr.to_id,c.id as contact_id,c.nickname contact_nickname,c.avatar as contact_avatar,c.corp_short_name as contact_corp_name,c.is_wechat as contact_is_wechat,sr.trigger_time,sr.content,sr.msg_total_count,sr.msg_sent_count,sr.status,sr.failure_reason')
            ->join('ch_contact as c',function ($join) use ($robotId){
                $join->on( 'sr.to_id', '=', 'c.user_id')->on('sr.robot_id','=','c.robot_id');
            })
            ->join('ch_robot as r', 'r.id', '=', 'sr.robot_id')
            ->where('sr.uid',$data['uid'])
            ->where('sr.type',$taskType)
            ->where('sr.task_id',$taskId)
            ->when(!empty($contactId),function ($query) use ($contactId){
                $query->where('c.id',$contactId);
            })->when(!empty($robotId),function ($query) use ($robotId){
                $query->where('sr.robot_id',$robotId);
            })->when(filled($status),function ($query) use ($status){
                $query->where('sr.status',$status);
            })->when(!empty($startTime) && !empty($endTime),function ($query) use ($startTime,$endTime){
                $query->whereBetween('sr.trigger_time',[strtotime($startTime),strtotime($endTime)]);
            })->orderBy('sr.trigger_time','desc')
            ->paginate($pageSize);

        $paginate->getCollection()->transform(function ($item){
            $item->trigger_time = datetime($item->trigger_time);
            $item->status_text = SendRecordStatusConstants::getMessage($item->status);
            return $item;
        });
        return $this->mapper->setPaginate($paginate);
    }

    public function addRecord(array $data): void
    {
        $uid = $data['uid'];
        $mainUid = $data['mainUid'];
        $taskId = $data['taskId'];
        $subTaskId = $data['subTaskId'];
        $recordData = $data['recordData'];
        $isSendNow = $data['isSendNow'];
        $isLastSubTask = $data['isLastSubTask'];
        $isRoom = $data['isRoom'];
        $type = $data['type'];
        $now = Carbon::now()->toDateTimeString();
        $totalCount = count($recordData);
        foreach ($recordData as $k=>$item){
            $recordData[$k]['content'] = json_encode($item['content'],JSON_UNESCAPED_UNICODE);
            !empty($item['extra']) && $recordData[$k]['extra']=json_encode($item['extra'],JSON_UNESCAPED_UNICODE);
            $recordData[$k]['created_at'] = $now;
            $recordData[$k]['updated_at'] = $now;
            if($k+1 == $totalCount){
                //是否最后一个发送对象
                $recordData[$k]['is_last_send_item'] = 1;
            }else{
                $recordData[$k]['is_last_send_item'] = 0;
            }
        }

        $robotIds = array_column($recordData,'robot_id');
        $this->mapper->model::insert($recordData);
        if($isSendNow){
            foreach ($robotIds as $robotId){
                $this->sendByTaskId((int)$robotId,$taskId,$subTaskId,$mainUid,$uid,$type,$isLastSubTask,$isRoom);
            }
        }
    }

    /**
     * 根据任务发送消息
     * @param int $robotId
     * @param int $taskId
     * @param int $subTaskId
     * @param int $uid
     * @param int $type
     * @param bool $isLastSubTask
     * @return void
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function sendByTaskId(int $robotId,int $taskId,int $subTaskId,int $mainUid,int $uid,int $type,bool $isLastSubTask = true,$isRoom=0)
    {
        //获取所有待发送的任务
        $list = $this->mapper->getPendingTasksByTaskId($taskId,$subTaskId,$robotId);
        if(empty($list)){
            $this->handleOtherEvents($taskId,$subTaskId,$type,$isLastSubTask);
        }
        //更新子任务和主任务状态
        $this->updateSubTaskStatus($taskId,$subTaskId,$type,$robotId);
        //获取发送配置
        $sendConfig = $this->getSendConfig($robotId,$mainUid,$uid,$type,$taskId);

        $needToSleep = $sendConfig['needToSleep'];
        if($needToSleep){
            return;
        }


        //更新发送状态
        $ids = $list->pluck('id')->toArray();
        $this->mapper->model::query()
            ->whereIn('id',$ids)
            ->update([
                'start_time' => time(),
                'status' => SendRecordStatusConstants::SENDING,
            ]);
        if($type==SendConfigConstants::SPEED_SENDING){
            //$this->sendSpeedMessageBatchV2($list,$sendConfig,$robotId,$taskId,$subTaskId,$isRoom,$isLastSubTask);
            return;
        }
        co(function ()use($list,$sendConfig,$isLastSubTask){
            $intervalMin = $sendConfig['intervalMin'];
            $intervalMax = $sendConfig['intervalMax'];
            foreach ($list as $k=>$item){
                if(empty($item['to_id'])){
                    continue;
                }
                //获取发送对象间隔
                $extra=data_get($item,'extra');
                if(!empty($extra['delay'])){
                    $sendObjectInterval=$extra['delay'];
                }else{
                    $interval = mt_rand((int)$intervalMin, (int)$intervalMax);
                    $sendObjectInterval = $interval;
                }
                Coroutine::sleep($sendObjectInterval);
                $data = $item->toArray();
                $data['is_last_sub_task'] = $isLastSubTask;
                $this->sendMessage($data);
            }
        });
    }


    /**
     * 根据任务发送消息(分页)
     * @param int $robotId
     * @param int $taskId
     * @param int $subTaskId
     * @param int $uid
     * @param int $type
     * @param bool $isLastSubTask
     * @param int $isRoom 0=客户  1=群  2=不区分群和客户
     * @param int $pageSize 每次发送多少条
     * @return void
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function sendByTaskIdPage(int $robotId,int $taskId,int $subTaskId,int $mainUid,int $uid,int $type,bool $isLastSubTask = true,int $isRoom=2,int $pageSize=1000)
    {
        //获取发送配置
        $sendConfig = $this->getSendConfig($robotId,$mainUid,$uid,$type,$taskId);
        $needToSleep = $sendConfig['needToSleep'];
        $robot = container()->get(ChRobotMapper::class)->findById($robotId);
        //机器人不在线或者休眠中直接返回
        if($needToSleep || $robot->login_status !=1){
            $this->updateSubTaskStatus($taskId,$subTaskId,$type,$robotId,$needToSleep);
            return;
        }

        $totalCount = $this->mapper->model::query()
            ->where('task_id',$taskId)
            ->when(!empty($subTaskId),function ($query) use ($subTaskId){
                $query->where('sub_task_id',$subTaskId);
            })
            ->where('robot_id',$robotId)
            ->where('status',SendRecordStatusConstants::WAITING)
            ->when($isRoom != 2,function ($query) use ($isRoom){
                $query->where('is_room',$isRoom);
            })
            ->count();
        //更新子任务和主任务状态
        $this->updateSubTaskStatus($taskId,$subTaskId,$type,$robotId,$needToSleep,$totalCount);
        $processedCount = 0;

        //获取所有待发送的任务
        $this->mapper->model::query()
            ->where('task_id',$taskId)
            ->when(!empty($subTaskId),function ($query) use ($subTaskId){
                $query->where('sub_task_id',$subTaskId);
            })
            ->where('robot_id',$robotId)
            ->where('status',SendRecordStatusConstants::WAITING)
            ->when($isRoom != 2,function ($query) use ($isRoom){
                $query->where('is_room',$isRoom);
            })
            ->chunkById($pageSize,function ($list) use ($robotId,$taskId,$subTaskId,$mainUid,$uid,$type,$isLastSubTask,$isRoom,$sendConfig,$totalCount,&$processedCount){
                //最后一个循环且是最后一次任务
                $isLast=false;
                $processedCount += count($list);
                //最后一个循环结束标志
                $isLastChunk = ($processedCount >= $totalCount);

                //更新发送状态
                $ids = $list->pluck('id')->toArray();
                $this->mapper->model::query()
                    ->whereIn('id',$ids)
                    ->update([
                        'start_time' => time(),
                        'status' => SendRecordStatusConstants::SENDING,
                    ]);
                //最后一个任务且是最后一次循环
                if($isLastChunk && $isLastSubTask){
                    $isLast=true;
                }
                if($type==SendConfigConstants::SPEED_SENDING){
                    co(function ()use($list,$sendConfig,$robotId,$taskId,$subTaskId,$isRoom,$isLastSubTask,$isLast){
                        $this->sendSpeedMessageBatchV2($list,$sendConfig,$robotId,$taskId,$subTaskId,$isRoom,$isLastSubTask,$isLast);
                    });
                    return;
                }
                //携程处理
                logger()->info('机器人开始发送' . $robotId);
                co(function ()use($list,$sendConfig,$isLastChunk,$isLastSubTask,$type,$taskId,$subTaskId){
                    $intervalMin = $sendConfig['intervalMin'];
                    $intervalMax = $sendConfig['intervalMax'];
                    $sendObjectInterval = 0;
                    $pauseIds=[];
                    $failIds=[];
                    foreach ($list as $k=>$item){
                        //暂停，未发送的全部改成待发送
                        if(container()->get(ChCrowSendingService::class)->getSendingPauseCache($taskId)){
                            $pauseIds[]=$item->id;
                            continue;
                        }
                        if(empty($item['to_id'])){
                            $item->status = SendRecordStatusConstants::FAILURE;
                            $item->failure_reason = '发送目标用户为空';
                            $item->save();
                            continue;
                        }
                        try {
                            //获取发送对象间隔
                            $extra=data_get($item,'extra');
                            if(!empty($extra['delay'])){
                                $sendObjectInterval=$extra['delay'];
                            }else{
                                $interval = mt_rand((int)$intervalMin, (int)$intervalMax);
                                $sendObjectInterval = $interval;
                            }
                            logger()->info('发送对象间隔' . $sendObjectInterval);
                            $k!=0 && Coroutine::sleep($sendObjectInterval);
                            $data = $item->toArray();
                            $data['is_last_sub_task'] = $isLastSubTask;
                            $this->sendMessage($data);
                        }catch (\Exception $e){
                            logger()->error("协程处理机器人发送异常:".$item->id.":".$e->getMessage());
                            $failIds[]=$item->id;
                            continue;
                        }
                    }
                    if($pauseIds){
                        $this->mapper->model::query()
                            ->whereIn('id',$pauseIds)
                            ->update([
                                'status' => SendRecordStatusConstants::WAITING,
                            ]);
                    }
                    if($failIds){
                        $this->mapper->model::query()
                            ->whereIn('id',$failIds)
                            ->update([
                                'status' => SendRecordStatusConstants::FAILURE,
                                'failure_reason' => '协程处理机器人发送异常',
                            ]);
                    }
                    //延迟30-40秒执行统计
                    container()->get(LowQueueService::class)->push(new CommonJob(new CommonJobDto(
                        classname: ChSendRecordService::class,
                        method: 'endTaskStatus',
                        data:[
                            'type' => $type,
                            'taskId' => $taskId,
                            'subTaskId' => $subTaskId,
                            'isLastChunk' => $isLastChunk,
                            'isLastSubTask' => $isLastSubTask,
                        ]
                    )),20+rand(10,20));
                });

            });

    }


    /**
     * 获取发送配置
     * @param int $robotId
     * @param int $mainUid
     * @param int $uid
     * @param int $type
     * @return array
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    private function getSendConfig(int $robotId,int $mainUid,int $uid,int $type,$taskId): array
    {
        $isMain = true;
        $getConfigUid = $mainUid;
        switch ($type){
            case SendConfigConstants::SMART_AUTO_PUSH:
            case SendConfigConstants::SMART_PUSH:
                $getConfigRobotId = 0;
                break;
            default:
                $getConfigRobotId = $robotId;
                break;
        }

        $sendConfig = container()->get(ChSendConfigService::class)->getConfig($type,$getConfigUid,$getConfigRobotId,$isMain);
        $needToSleep = false;
        if(!empty($sendConfig)){
            //休眠时间段开关
            !empty($sendConfig['sleep_period_switch']) && $needToSleep = is_sleep_needed($sendConfig['sleep_period_switch'],$sendConfig['sleep_period_cfg']);
            $intervalMin = !empty($sendConfig['send_object_interval_min'])?$sendConfig['send_object_interval_min']:0;
            $intervalMax = !empty($sendConfig['send_object_interval_max'])?$sendConfig['send_object_interval_max']:0;
        }else{
            $intervalMin = 0;
            $intervalMax = 0;
        }

        if($type == SendConfigConstants::HIGH_SENDING){
            //高级群发 自定义对象发送间隔
           $crowdSendingInfo =  ChCrowdSending::query()
                ->select(['send_limit_type','send_limit_conf'])
                ->where('id',$taskId)
                ->first();
           if($crowdSendingInfo['send_limit_type'] == 2){
               $intervalMin = $crowdSendingInfo['send_limit_conf']['send_object_min'];
               $intervalMax = $crowdSendingInfo['send_limit_conf']['send_object_max'];
           }
        }


        return [
            'needToSleep' => $needToSleep,
            'intervalMin' => $intervalMin,
            'intervalMax' => $intervalMax,
        ];
    }

    private function handleOtherEvents(int $taskId,int $subTaskId,int $type,bool $isLastSubTask = true): void
    {
        switch ($type){
            case SendConfigConstants::SMART_PUSH:
                //智能推送
                ChSmartPushSchemeSubTask::query()
                    ->where('id',$subTaskId)
                    ->update([
                        'status' => SmartPushSchemeSubStatusConstants::COMPLETED
                    ]);
                if($isLastSubTask){
                    $subInfo = ChSmartPushSchemeSubTask::query()
                        ->with(['scheme'=>function ($query) {
                            $query->select(['id','push_type']);
                        }])
                        ->where('id',$subTaskId)
                        ->first();
                    $update['is_running'] = 0;
                    if($subInfo['scheme']['push_type'] == SmartPushSchemeTypeConstants::TIMING_SINGLE){
                        $update['status'] = SmartPushSchemeStatusConstants::COMPLETED;
                    }

                    if($subInfo->scheme->push_type == SmartPushSchemeTypeConstants::TIMING_REPEAT){
                        ChSmartPushSchemeTask::query()->where('id',$subInfo->task_id)->update([
                            'status' =>  SmartPushSchemeTaskStatusConstants::COMPLETED
                        ]);
                    }

                    ChSmartPushScheme::query()
                        ->where('id',$taskId)
                        ->update($update);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 发送消息
     * @param array $data
     * @return void
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function sendMessage(array $data): void
    {
        $content = $data['content'];
        $count = count($content);
        foreach ($content as $k => $item){
            //消息发送间隔
            if(isset($item['extra']['limit'])){
                $limit = $item['extra']['limit'];
                $limitUnit = (int)data_get($limit,'unit',1);
                $limitValue = data_get($limit,'value',10);
                $intervalTime = $this->getSeconds($limitUnit,$limitValue);
            }else{
                $intervalTime = mt_rand(3,5);
            }
            $isLastMsg = false;
            if($count == $k+1){
                $isLastMsg = true;
            }
            logger()->info('消息发送间隔' . $intervalTime .'秒');
            $k!=0 && Coroutine::sleep($intervalTime);
            $dataSend=[
                'record_id'=> $data['id'],
                'msg_type' => $item['msg_type'],
                'content' => $item['content'],
                'filename' => $item['file_name'] ?? '',
                'is_last_msg' => $isLastMsg,
                'is_last_sub_task' => $data['is_last_sub_task']
            ];
            container()->get(SendRecordMessageHandlerService::class)->handle($dataSend);
            //container()->get(Producer::class)->produce(new RobotMsgProducers($data,$intervalTime));
        }
    }


    public function sendSpeedMessageBatch($list,$sendConfig,$robotId,$taskId,$subTaskId,$isRoom,$isLastSubTask=false): void
    {
        $list=$list->toArray();
        $chunkSize = 200;
        $total = count($list);
        $delay=0;
        $intervalMin = $sendConfig['intervalMin'];
        $intervalMax = $sendConfig['intervalMax'];
        $isEnd=false;
        $isSubEnd=false;
        for ($i = 0; $i < $total; $i += $chunkSize) {
            // 使用 array_slice 取出200个元素
            //$chunk = array_slice($list, $i, $chunkSize);
            //$columnIds = array_column($chunk,'to_id');
            //用极速群发统一发送
            if($total-$i <= 200){
                $isSubEnd=true;
            }
            if($isLastSubTask && $isSubEnd){
                $isEnd=true;
            }
            container()->get(LowQueueService::class)->push(new CommonJob(new CommonJobDto(
                classname: ChCrowSendingService::class,
                method: 'speedSendMessage',
                data:[
                    'robot_id' => $robotId,
                    'task_id' => $taskId,
                    'sub_task_id' => $subTaskId,
                    'is_room' => $isRoom,
                    'start' => 0,
                    'limit' => $chunkSize,
                    'is_end' => $isEnd,
                    'is_sub_end' => $isSubEnd,
                ]
            )),$delay);
            $delay += mt_rand($intervalMin,$intervalMax);
        }
    }


    public function sendSpeedMessageBatchV2($list,$sendConfig,$robotId,$taskId,$subTaskId,$isRoom,$isLastSubTask=false,$isLast=false): void
    {
        $intervalMin = $sendConfig['intervalMin'];
        $intervalMax = $sendConfig['intervalMax'];
        $data=[
            'robot_id' => $robotId,
            'task_id' => $taskId,
            'sub_task_id' => $subTaskId,
            'is_room' => $isRoom,
            'is_end' => $isLast,
            'is_last_sub_task' => $isLastSubTask,
        ];
        //暂停，未发送的全部改成待发送
        if(container()->get(ChCrowSendingService::class)->getSendingPauseCache($taskId)){
            $sendRecordList = $list->pluck('id');
            $this->mapper->model::query()
                ->whereIn('id',$sendRecordList)
                ->update([
                    'status' => SendRecordStatusConstants::WAITING,
                ]);
            return;
        }
        $sendObjectInterval = mt_rand((int)$intervalMin,(int)$intervalMax);
        logger()->info('极速群发发送对象间隔' . $sendObjectInterval);
        Coroutine::sleep($sendObjectInterval);
        container()->get(ChCrowSendingService::class)->speedSendMessageV2($data,$list);
    }

    /**
     * 更新任务状态
     * @param int $taskId
     * @param int $subTaskId
     * @param int $type
     * @param bool $isLastSubTask
     * @param int $isRoom
     */
    private function updateSubTaskStatus(int $taskId,int $subTaskId,int $type,int $robotId,$needToSleep=false,$totalCount=0): void
    {
        switch ($type){
            case SendConfigConstants::HIGH_SENDING:
                DB::transaction(function () use ($taskId, $subTaskId, $totalCount,$robotId,$needToSleep) {
                    $subTask=ChCrowdSendingSubTask::find($subTaskId);
                    if(empty($subTask)) return;
                    $robot = container()->get(ChRobotMapper::class)->findById($robotId);
                    if($needToSleep || $robot->login_status !=1){
                        //机器人不在线暂停
                        $subTask->update(['status' => CrowSendingConstants::PAUSE]);
                        ChCrowdSending::query()->where('id',$taskId)->update(['status' => CrowSendingConstants::PAUSE]);
                        return;
                    }
                    $subTask->update(['status' => CrowSendingConstants::SENDING]);
                    //$subTask->increment('complete_total',$totalCount);
                    //$task->increment('complete_total',$totalCount);
                });
                break;
            case SendConfigConstants::SPEED_SENDING:
                DB::transaction(function () use ($taskId, $subTaskId, $totalCount,$robotId,$needToSleep) {
                    $subTask=ChCrowdSendingSubTask::find($subTaskId);
                    if(empty($subTask)) return;
                    $robot = container()->get(ChRobotMapper::class)->findById($robotId);
                    if($needToSleep || $robot->login_status !=1){
                        //机器人不在线暂停
                        $subTask->update(['status' => CrowSendingConstants::PAUSE]);
                        ChCrowdSending::query()->where('id',$taskId)->update(['status' => CrowSendingConstants::PAUSE]);
                    }
                    $subTask->update(['status' => CrowSendingConstants::SENDING]);
                });
            default:
                break;
        }
    }


    public function endTaskStatus($data): void
    {
        logger()->info('延迟30s处理群发统计'.$data['subTaskId']);
        $type=$data['type'];
        $taskId=$data['taskId'];
        $subTaskId=$data['subTaskId'];
        $isLastChunk=$data['isLastChunk'];
        $isLastSubTask=$data['isLastSubTask'];
        switch ($type){
            case SendConfigConstants::HIGH_SENDING:
                if($isLastChunk && $isLastSubTask){
                    //全部结束
                    $success_total=$this->mapper->model::query()->where('type',SendConfigConstants::HIGH_SENDING)->where('task_id',$taskId)->where('status',SendRecordStatusConstants::SUCCESS)->count();
                    $fail_total=$this->mapper->model::query()->where('type',SendConfigConstants::HIGH_SENDING)->where('task_id',$taskId)->where('status',SendRecordStatusConstants::FAILURE)->count();
                    $up=[
                        'success_total' => $success_total,
                        'fail_total' => $fail_total,
                        'complete_total' => $success_total + $fail_total,
                    ];
                    if(!container()->get(ChCrowSendingService::class)->getSendingPauseCache($taskId)){
                        $up['status']=CrowSendingConstants::COMPLETE;
                    }
                    ChCrowdSending::query()->where('id',$taskId)->update($up);
                }
                if($isLastChunk){
                    //子任务结束
                    $sub_success_total=$this->mapper->model::query()->where('type',SendConfigConstants::HIGH_SENDING)->where('sub_task_id',$subTaskId)->where('status',SendRecordStatusConstants::SUCCESS)->count();
                    $sub_fail_total=$this->mapper->model::query()->where('type',SendConfigConstants::HIGH_SENDING)->where('sub_task_id',$subTaskId)->where('status',SendRecordStatusConstants::FAILURE)->count();
                    $up=[
                        'success_total' => $sub_success_total,
                        'fail_total' => $sub_fail_total,
                        'complete_total' => $sub_success_total + $sub_fail_total,
                    ];
                    if(!container()->get(ChCrowSendingService::class)->getSendingPauseCache($taskId)){
                        $up['status']=CrowSendingConstants::COMPLETE;
                    }
                    ChCrowdSendingSubTask::query()->where('id',$subTaskId)->update($up);
                }
                break;
            default:
                break;
        }
    }

    private function getSeconds($unit,$value): float|int
    {
        return (int)match ($unit) {
            2 => $value * 60,
            3 => $value * 60 * 60,
            default => $value,
        };
    }
}